package work.linruchang.oauthclientproject.config.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import work.linruchang.oauthclientproject.config.handler.SysetmBaseCustomException;
import work.linruchang.oauthclientproject.config.oauth.OtherSysUser;
import work.linruchang.oauthclientproject.config.oauth.RequestEnum;
import work.linruchang.oauthclientproject.config.oauth.ResponseResult;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.stream.Stream;

/**
 * Oauth认证
 *
 * @author LinRuChang
 * @version 1.0
 * @date 2022/08/04
 * @since 1.8
 **/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class OauthAuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean authStatusFlag = false;

        //登录成功时用户信息都存入内存无需从数据库拿取
        HttpSession session = request.getSession();
        OtherSysUser otherSysUser = (OtherSysUser) session.getAttribute("otherSysUser");


        Cookie[] cookies = ObjectUtil.defaultIfNull(request.getCookies(), new Cookie[0]);
        String cookieUserName = Stream.of(cookies)
                .filter(cookie -> StrUtil.equals(cookie.getName(), "userName"))
                .findFirst()
                .map(Cookie::getValue)
                .orElse(null);

        if (otherSysUser != null) {
            authStatusFlag = true;
        }


        //认证失败 == 重定向到登录页面
        if (!authStatusFlag) {
            response.setHeader("Content-Type", "application/json;charset=UTF-8");
            SysetmBaseCustomException sbce = new SysetmBaseCustomException(RequestEnum.ResponseCodeEnum.UN_AUTHORIZED);
            response.getWriter().write(JSONUtil.toJsonStr(ResponseResult.builder()
                    .code(sbce.getCode())
                    .message(StrUtil.blankToDefault(sbce.getResponseCodeEnum().getDescription(), sbce.getMessage()))
                    .success(false)
                    .result("失败")
                    .build()));
            return false;
        }

        return authStatusFlag;
    }
}
